<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable class="!w-240px">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_CONTRACT_ARCHIVE_EXPENSE_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="contentDate">
          <el-date-picker
            v-model="queryParams.contentDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['san:biz-contract-archive:expense']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['san:biz-contract-archive:expense']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
          <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['san:biz-contract-archive:expense']"
          >
            <Icon icon="ep:delete" class="mr-5px" /> 批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <!-- 统计 -->
    <ContentWrap>
      <el-row style="text-align: center">
        <el-col :span="8"
          ><span>合计其他：{{ totalOthers }}</span></el-col
        >
        <el-col :span="8"
          ><span>合计差旅费：{{ totalTravel }}</span></el-col
        >
        <el-col :span="8"
          ><span>合计外包费：{{ totalOutsourcing }}</span></el-col
        >
      </el-row>
    </ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.BIZ_CONTRACT_ARCHIVE_EXPENSE_TYPE" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="是否完成支付" align="center" prop="isPaid">
          <template #default="scope">
            <dict-tag
              :type="DICT_TYPE.BIZ_CONTRACT_ARCHIVE_EXPENSE_IS_PAID"
              :value="scope.row.isPaid"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="money" />
        <el-table-column label="收款方" align="center" prop="receiver" />
        <el-table-column label="内容" align="center" prop="content" />
        <el-table-column
          label="日期"
          align="center"
          prop="contentDate"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="支付确认人" align="center" prop="confirmPerson" />
        <el-table-column
          label="支付确认时间"
          align="center"
          prop="confirmDate"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['san:biz-contract-archive:expense']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['san:biz-contract-archive:expense']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <ContractArchiveExpenseForm ref="formRef" @success="getList" />
    <template #footer>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ContractArchiveExpenseApi, ContractArchiveExpense } from '@/api/biz/contract/expense'
import ContractArchiveExpenseForm from './expense/ContractArchiveExpenseForm.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

/** 合同档案-支出 列表 */
defineOptions({ name: 'ContractArchiveExpense' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContractArchiveExpense[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractArchiveId: undefined,
  name: undefined,
  type: undefined,
  isPaid: undefined,
  money: undefined,
  receiver: undefined,
  content: undefined,
  contentDate: [],
  confirmPerson: undefined,
  confirmDate: [],
  remark: undefined,
  createTime: []
})
const contractArchiveId = ref()
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题

const totalOthers = ref(0.0) // 合计其他
const totalTravel = ref(0.0) // 合计差旅费
const totalOutsourcing = ref(0.0) // 合计外包费

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '费用支出'
  contractArchiveId.value = id
  queryParams.contractArchiveId = contractArchiveId.value
  handleQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  totalOthers.value = 0.0
  totalTravel.value = 0.0
  totalOutsourcing.value = 0.0
  try {
    const data = await ContractArchiveExpenseApi.getContractArchiveExpensePage(queryParams)
    list.value = data.list
    total.value = data.total
    if (data.list.length > 0) {
      data.list.forEach((element) => {
        if (element.type == '1') {
          totalOthers.value += element.money
        }
        if (element.type == '2') {
          totalTravel.value += element.money
        }
        if (element.type == '3') {
          totalOutsourcing.value += element.money
        }
      })
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (type == 'create') {
    formRef.value.open(type, id, contractArchiveId.value)
  } else {
    formRef.value.open(type, id)
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractArchiveExpenseApi.deleteContractArchiveExpense(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除合同档案-支出 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ContractArchiveExpenseApi.deleteContractArchiveExpenseList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ContractArchiveExpense[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractArchiveExpenseApi.exportContractArchiveExpense(queryParams)
    download.excel(data, '合同档案-支出.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const cancel = () => {
  dialogVisible.value = false
  resetQuery()
}
</script>
